// 存储上下文状态
let extensionState = {
    initialized: false
};

// 初始化插件
const initializeExtension = () => {
    chrome.storage.sync.get(['enabled', 'maxWidth', 'whitelist'], (result) => {
        // 设置默认值
        if (typeof result.enabled === 'undefined') {
            chrome.storage.sync.set({
                enabled: false,
                maxWidth: 1000,
                whitelist: []
            });
        }
        extensionState.initialized = true;
    });
};

// 检查URL是否在白名单中
const isUrlInWhitelist = async (url) => {
    const hostname = new URL(url).hostname;
    const result = await chrome.storage.sync.get(['whitelist']);
    const whitelist = result.whitelist || [];
    return whitelist.includes(hostname);
};

// 更新图标状态
const updateIcon = async (tabId, enabled) => {
    const iconPath = enabled ? {
        16: "icons/icon16.png",
        48: "icons/icon48.png",
        128: "icons/icon128.png"
    } : {
        16: "icons/icon16-disabled.png",
        48: "icons/icon48-disabled.png",
        128: "icons/icon128-disabled.png"
    };

    await chrome.action.setIcon({
        tabId: tabId,
        path: iconPath
    });
};

// 处理标签页更新
const handleTabUpdate = async (tabId, changeInfo, tab) => {
    // 只在页面完全加载时处理
    if (changeInfo.status === 'complete' && tab.url) {
        try {
            // 检查是否是可优化的页面
            if (tab.url.startsWith('http') || tab.url.startsWith('https')) {
                const result = await chrome.storage.sync.get(['enabled']);
                const inWhitelist = await isUrlInWhitelist(tab.url);
                
                // 更新图标状态
                await updateIcon(tabId, result.enabled && !inWhitelist);

                // 如果插件已启用且不在白名单中，应用优化
                if (result.enabled && !inWhitelist) {
                    chrome.tabs.sendMessage(tabId, {
                        type: 'TOGGLE_OPTIMIZATION',
                        enabled: true,
                        maxWidth: result.maxWidth || 1000
                    });
                }
            }
        } catch (error) {
            console.error('Error handling tab update:', error);
        }
    }
};

// 监听标签页更新
chrome.tabs.onUpdated.addListener(handleTabUpdate);

// 监听插件安装/更新
chrome.runtime.onInstalled.addListener((details) => {
    if (details.reason === 'install') {
        // 首次安装
        initializeExtension();
        // 显示欢迎页面或设置页面
        chrome.tabs.create({
            url: 'welcome.html'
        });
    } else if (details.reason === 'update') {
        // 版本更新
        // 可以在这里处理配置迁移
        initializeExtension();
    }
});

// 监听消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.type === 'GET_TAB_INFO') {
        // 返回当前标签页信息
        chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
            if (tabs[0]) {
                sendResponse({
                    url: tabs[0].url,
                    id: tabs[0].id
                });
            }
        });
        return true; // 保持消息通道开放
    }
    
    if (request.type === 'UPDATE_ICON') {
        // 更新图标状态
        updateIcon(sender.tab.id, request.enabled);
        sendResponse({ success: true });
        return true;
    }
});

// 监听存储变化
chrome.storage.onChanged.addListener((changes, namespace) => {
    if (namespace === 'sync') {
        // 当设置发生变化时，更新所有标签页
        if (changes.enabled || changes.maxWidth || changes.whitelist) {
            chrome.tabs.query({}, (tabs) => {
                tabs.forEach(tab => {
                    if (tab.url && (tab.url.startsWith('http') || tab.url.startsWith('https'))) {
                        handleTabUpdate(tab.id, { status: 'complete' }, tab);
                    }
                });
            });
        }
    }
});

// 错误处理
const handleError = (error) => {
    console.error('Background Script Error:', error);
    // 可以在这里添加错误报告逻辑
};

// 设置全局错误处理
self.onerror = (message, source, lineno, colno, error) => {
    handleError(error);
    return true;
};

// Service Worker 激活时的处理
self.addEventListener('activate', (event) => {
    // 确保Service Worker立即激活
    event.waitUntil(clients.claim());
}); 